#include "ws2812.h"
#include "system.h"
void ws2812_gpio_init()
{
    gpio_init(GPIOE, PIN6, GPIO_MODE_OUTPUT, GPIO_PULL_UP, GPIO_DRV_3); // PE6 OUT.
}

void ws2812_reset()
{
    DOUTH;
    DOUTL;
    for (volatile int j = 0; j < 300; j++)
    {
        asm volatile("NOP");
    }
}

void ws2812_write_24bit(int grb)
{
    volatile int i = 0, j = 0;
    int temp = grb;

    for (; i < 24; i++)
    {
        if (temp & 0x800000)
        {
            DOUTH;
            for (j = 0; j < 22; j++) // 600ns
            {
                asm volatile("NOP");
            }
            DOUTL;
            temp = temp << 1; //+一起 600+ if
            for (j = 0; j < 21; j++)
            {
                asm volatile("NOP");
            }
        }
        else
        {
            DOUTH;
            for (j = 0; j < 7; j++)
            {
                asm volatile("NOP");
            }
            DOUTL;
            temp = temp << 1; //+一起 800+ if
            for (j = 0; j < 42; j++)
            {
                asm volatile("NOP");
            }
        }
    }
}

void ws2812_write(int grb[], uint32_t length)
{
    for (int i = 0; i < length; i++)
    {
        ws2812_write_24bit(grb[i]);
    }
}

// 流水灯
void swap_grb(int grb[], uint32_t length)
{
    int temp = grb[length - 1];
    for (uint32_t i = length - 1; i > 0; i--) // 交换length -1 次
    {
        grb[i] = grb[i - 1];
    }
    grb[0] = temp; // 第0个和最后一个交换
}